from django.shortcuts import render, HttpResponse
from django_redis import get_redis_connection
from utils.restful import result
from db.models import Goods
import datetime
from db.models import Address


def udai_shopcart(request):
    """
    购物车主页
    :param request:
    :return:
    """
    user = request.user
    if not user.is_authenticated:
        return render(request, 'login/login.html')

    cart_key = "cart_%d" % user.id
    conn = get_redis_connection('default')

    cart_info = conn.hgetall(cart_key)
    print(cart_info)
    data = []
    mse = {}
    for i in cart_info:
        context = {}
        print(i)
        info = eval(conn.hget(cart_key, i).decode('utf-8'))
        context['goods'] = Goods.objects.get(pk=i)
        context['color'] = info[1]
        context['size'] = info[2]
        context['num'] = info[0]
        data.append(context)
    mse['data'] = data
    mse['count_num'] = conn.hlen(cart_key)
    print(mse)
    return render(request, 'shippingcart/udai_shopcart.html', mse)


def udai_cart_ack(request):
    '''
    提交订单
    :param request:
    :return:
    '''
    user = request.user
    if not user.is_authenticated:
        return render(request, 'login/login.html')
    sku_id = dict(request.POST)
    addr = Address.objects.filter(user=request.user)
    print(sku_id)
    print(sku_id['sku_id'])
    cart_key = 'cart_%d' % request.user.id
    conn = get_redis_connection('default')
    try:
        num = sku_id['number'][0]
        color = sku_id['sku_colsize'][0][:2]
        size = sku_id['sku_colsize'][0][-1]
        sku = sku_id['sku_id'][0]
        data = []
        mse = {}
        count_pice = 0

        context = {}

        goods = Goods.objects.get(pk=sku)

        context['goods'] = goods
        context['color'] = color
        context['size'] = size
        context['num'] = num
        print(num)
        context['price'] = int(num) * int(goods.price)
        count_pice += int(num) * int(goods.price)
        data.append(context)
        print(data)
        # 订单号生成
        # order_no = str(time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))) + str(time.time()).replace('.', '')[-7:]

        mse['data'] = data
        # mse['order_on'] = order_no
        mse['addr'] = addr
        mse['time'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        mse['count_pice'] = count_pice
        print(mse)

        # print(cart_list[2].encode('utf-8').encode('utf-8'))


        # 设置hash中sku_id对应的值
        conn.hset(cart_key, sku, str([num, color, size]))
        return render(request, 'shippingcart/udai_shopcart_pay.html', mse)
    except:


        data = []
        mse = {}
        count_pice = 0
        for i in sku_id['sku_id']:
            context = {}
            print(i)
            goods = Goods.objects.get(pk=i)
            info = eval(conn.hget(cart_key, i).decode('utf-8'))
            context['goods'] = goods
            context['color'] = info[1]
            context['size'] = info[2]
            context['num'] = info[0]
            context['price'] = int(info[0]) * int(goods.price)
            count_pice += int(info[0]) * int(goods.price)
            data.append(context)
            print(data)
        # 订单号生成
        # order_no = str(time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))) + str(time.time()).replace('.', '')[-7:]

        mse['data'] = data
        # mse['order_on'] = order_no
        mse['addr'] = addr
        mse['time'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        mse['count_pice'] = count_pice
        print(mse)
        return render(request, 'shippingcart/udai_shopcart_pay.html', mse)


def udai_addcart(request):
    '''
    1. 获取用户登录信息user
    2.获取物品信息,物品数量,创建购物车对象
    <QueryDict: {'csrfmiddlewaretoken': ['88Jr0EL5CBD7npGSrODNl3sllqtbxDmccA8oSXpnmdQuNWAsD5BT0PXm4u89ENM8'],
    'sku_id': ['1'], 'number': ['1'], 'sku_colsize': ['白色M']}>
    '''
    user = request.user
    if not user.is_authenticated:
        return render(request, 'login/login.html')
    # 接收数据
    print(request.POST)
    sku_id = request.POST.get('sku_id')
    count = request.POST.get('number')
    sku_colorsize = request.POST.get('sku_colsize')

    print(sku_id, count, sku_colorsize)
    # 数据效验
    if not all([sku_id, count]):
        return result({'res': 1, 'errmsg': '数据不完整'})
    # 校检添加商品的数量
    try:
        count = int(count)
    except Exception as e:
        return result({'res': 2, 'errmsg': '商品数目出错'})
    # 校验商品是否存在
    try:
        sku = Goods.objects.get(id=sku_id)
    except Goods.DoesNotExist:
        return result({'res': 3, 'errmsg': '商品不存在'})
    # 业务处理:添加购物车记录
    conn = get_redis_connection('default')#,'raw'
    cart_key = 'cart_%d' % user.id

    # 先尝试获取sku_id的值--> hget cart_key sku_id
    # 如果sku_id在hash中不存在,hget返回none
    cart_list = conn.hget(cart_key, sku_id)
    # print(cart_list[2].encode('utf-8').encode('utf-8'))

    if cart_list:
        cart_list = eval(cart_list.decode('utf-8'))
        count += cart_list[0]
    # 设置hash中sku_id对应的值
    conn.hset(cart_key, sku_id, str([count, sku_colorsize[:2], sku_colorsize[-1]]))

    # 返回应答
    return result({'res': 5, }, message='添加成功')


def check_num(request):
    '''
    修改商品数量
    post数据
    <QueryDict: {'csrfmiddlewaretoken': ['uddDrNLS440dUnjCsPPP16eIdt2uYX3JyFCAj6paOGdAkUdcE6NVGSJJWxHs57tF'],
    'sku_id': ['1'], 'number': ['1']}>

    :param request:
    :return:
    '''
    user = request.user
    if not user.is_authenticated:
        return render(request, 'login/login.html')
    crat_key = 'cart_%d' % user.id
    info = request.POST
    sku_id = info['sku_id']
    # 创建redis连接
    conn = get_redis_connection('default')
    # 获取用户购物车数据并变成列表,decode十六进制解码
    cart_list = eval(conn.hget(crat_key, sku_id).decode('utf-8'))
    cart_list[0] = info['number']
    conn.hset(crat_key, sku_id, str(cart_list))
    print(cart_list)
    return HttpResponse(result(message='更改成功'))


def del_cart(request):
    '''
    删除购物车记录
    ajax post请求 获取 商品id
    :param request:
    :return:
    '''
    user = request.user
    if not user.is_authenticated:
        return render(request, 'login/login.html')
    cart_key = 'cart_%d' % user.id

    sku_id = request.POST.get('sku_id')

    conn = get_redis_connection('default')
    if sku_id == 'all':
        for i in conn.hgetall(cart_key):

            conn.hdel(cart_key,i)
            cart_len = conn.hdel(cart_key, i)
            print(cart_len)
        return HttpResponse(result(message='删除成功'))
    cart_len = conn.hdel(cart_key, sku_id)
    print(cart_len)
    return HttpResponse(result(message='删除成功'))
